/*
  学习目标：重构封装actionType
*/
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getChannelListCreator, setCurrentCreator } from './store/action/channel';
import { getNewsById } from './store/action/news';
import defImgSrc from './assets/defaultCover.jpg';
export default function App() {
  return (
    <>
      <Header />
      <Main />
    </>
  );
}
function Main() {
  const { current } = useSelector((state) => state.channel);
  const dispatch = useDispatch();
  useEffect(() => {
    // 3 useEffect监控current，current变化时触发异步action
    dispatch(getNewsById(current));
  }, [current, dispatch]);

  //     6. 取出数据渲染
  const { list } = useSelector((state) => state.news);
  return (
    <div className="list">
      {list.map((item) => {
        return (
          <div key={item.art_id} className="article_item">
            <h3 className="van-ellipsis">{item.title}</h3>
            <div className="img_box">
              <img
                className="w100"
                src={item.cover.images ? item.cover.images[0] : defImgSrc}
                alt=""
              />
            </div>
            <div className="info_box">
              <span>{item.aut_name}</span>
              <span>{item.comm_count}评论</span>
              <span>{item.pubdate}</span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function Header() {
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getChannelListCreator());
  }, [dispatch]);

  const { list, current } = useSelector((state) => state.channel);

  return (
    <ul className="category">
      {list.map((item) => {
        return (
          <li
            onClick={() => dispatch(setCurrentCreator(item.id))}
            className={item.id === current ? 'select' : ''}
            key={item.id}
          >
            {item.name}
          </li>
        );
      })}
    </ul>
  );
}
